import json
import os
from typing import List, Optional, Set

from PySide6.QtCore import QModelIndex, QTimer, Qt
from PySide6.QtGui import QAction, QKeySequence, QShortcut
from PySide6.QtWidgets import (QApplication, QDialog, QFileDialog, QHBoxLayout,
                               QInputDialog, QLabel, QMainWindow, QMenu,
                               QMessageBox, QProgressBar, QPushButton, QSizePolicy,
                               QSplitter, QStatusBar, QToolBar, QVBoxLayout, QWidget,
                               QTabWidget, QTreeView)

from typing import Optional, Set
import os

from src.backend.data_manager import DataManager
from src.backend.undo_manager import UndoManager, OperationType
from src.frontend.table_model import TableModel
from src.frontend.table_view import TableView
from src.frontend.change_history_dialog import ChangeHistoryDialog
from src.frontend.record_dialog import RecordDialog
from src.column_marker_dialog import ColumnMarkerDialog
from src.frontend.insert_column_dialog import InsertColumnDialog


class MainWindow(QMainWindow):
    """主窗口 - 整合前后端"""
    
    def __init__(self):
        super().__init__()
        
        # 初始化事件总线
        from src.event_bus import EventBus
        self.event_bus = EventBus()
        
        # 初始化后端组件
        from src.backend.data_manager import DataManager
        self._data_manager = DataManager(event_bus=self.event_bus)
        from src.backend.undo_manager import UndoManager
        self._undo_manager = UndoManager(self._data_manager)
        
        # 初始化事件处理器
        from src.event_handlers import FrontendEventHandler
        self.event_handler = FrontendEventHandler(self)
        
        # 订阅事件
        from src.events import (
            CellEditedEvent, RowAddedEvent, RowInsertedEvent, RowDeletedEvent,
            ColumnAddedEvent, ColumnInsertedEvent, ColumnRemovedEvent,
            ColumnReorderedEvent, ColumnMarkedEvent, RowStatusChangedEvent,
            DataLoadedEvent, DataSavedEvent
        )
        
        self.event_bus.subscribe(CellEditedEvent, self.event_handler.handle_cell_edited)
        self.event_bus.subscribe(RowAddedEvent, self.event_handler.handle_row_added)
        self.event_bus.subscribe(RowInsertedEvent, self.event_handler.handle_row_inserted)
        self.event_bus.subscribe(RowDeletedEvent, self.event_handler.handle_row_deleted)
        self.event_bus.subscribe(ColumnReorderedEvent, self.event_handler.handle_column_reordered)
        self.event_bus.subscribe(ColumnMarkedEvent, self.event_handler.handle_column_marked)
        self.event_bus.subscribe(ColumnInsertedEvent, self.event_handler.handle_column_inserted)
        
        # 初始化前端组件
        self._model: Optional[TableModel] = None
        self._fixed_view: Optional[TableView] = None
        self._scroll_view: Optional[TableView] = None
        self._frozen_columns = 0
        
        # 设置窗口
        self.setWindowTitle("Qtable - 数据表格编辑器")
        self.setMinimumSize(1200, 800)
        
        # 设置UI
        self._setup_ui()
        self._setup_statusbar()
        self._setup_shortcuts()
        
        # 初始化表格
        self._init_table()
        
        # 定时器用于更新状态栏
        self._status_timer = QTimer()
        self._status_timer.timeout.connect(self._update_status)
        self._status_timer.start(1000)  # 每秒更新一次
        
    def _setup_ui(self):
        """设置UI"""
        central_widget = QWidget()
        self.setCentralWidget(central_widget)
        
        layout = QVBoxLayout(central_widget)
        
        # 工具栏区域
        toolbar_layout = QHBoxLayout()
        
        # 文件操作按钮
        open_btn = QPushButton("打开文件")
        open_btn.clicked.connect(self._open_file)
        toolbar_layout.addWidget(open_btn)
        
        save_btn = QPushButton("保存文件")
        save_btn.clicked.connect(self._save_file)
        toolbar_layout.addWidget(save_btn)
        
        toolbar_layout.addStretch()
        
        # 编辑操作按钮
        undo_btn = QPushButton("撤销")
        undo_btn.clicked.connect(self._undo)
        toolbar_layout.addWidget(undo_btn)
        
        redo_btn = QPushButton("重做")
        redo_btn.clicked.connect(self._redo)
        toolbar_layout.addWidget(redo_btn)
        
        toolbar_layout.addStretch()
        
        add_row_btn = QPushButton("添加行")
        add_row_btn.clicked.connect(self._add_row)
        toolbar_layout.addWidget(add_row_btn)
        
        add_col_btn = QPushButton("添加列")
        add_col_btn.clicked.connect(self._add_column)
        toolbar_layout.addWidget(add_col_btn)
        
        insert_col_btn = QPushButton("插入列")
        insert_col_btn.clicked.connect(self._insert_column)
        toolbar_layout.addWidget(insert_col_btn)
        
        insert_row_btn = QPushButton("插入行")
        insert_row_btn.clicked.connect(self._insert_row)
        toolbar_layout.addWidget(insert_row_btn)
        
        toolbar_layout.addStretch()
        
        # 行操作按钮
        disable_rows_btn = QPushButton("禁用行")
        disable_rows_btn.clicked.connect(self._disable_selected_rows)
        toolbar_layout.addWidget(disable_rows_btn)
        
        enable_rows_btn = QPushButton("启用行")
        enable_rows_btn.clicked.connect(self._enable_selected_rows)
        toolbar_layout.addWidget(enable_rows_btn)
        
        toolbar_layout.addStretch()
        
        # 列操作按钮
        mark_columns_btn = QPushButton("列标识设置")
        mark_columns_btn.clicked.connect(self._set_column_markers)
        toolbar_layout.addWidget(mark_columns_btn)
        
        # 变更历史按钮
        history_btn = QPushButton("变更历史")
        history_btn.clicked.connect(self._show_change_history)
        toolbar_layout.addWidget(history_btn)
        
        # Record按钮
        record_btn = QPushButton("Record")
        record_btn.clicked.connect(self._show_record)
        toolbar_layout.addWidget(record_btn)
        
        layout.addLayout(toolbar_layout)
        
        # 创建Tab控件
        self.tab_widget = QTabWidget()
        layout.addWidget(self.tab_widget)
        
        # 创建表格Tab
        self._setup_table_tab()
        
        # 创建TreeView Tab
        self._setup_treeview_tab()
        
    def _setup_table_tab(self):
        """设置表格Tab"""
        # 创建表格Tab的widget
        table_widget = QWidget()
        table_layout = QVBoxLayout(table_widget)
        
        # 创建分割器
        table_splitter = QSplitter()
        table_splitter.setOrientation(Qt.Horizontal)
        table_splitter.setChildrenCollapsible(False)
        
        # 固定视图（冻结列）
        self._fixed_view = TableView()
        self._fixed_view.column_moved.connect(self._on_column_moved)
        self._fixed_view.row_deleted.connect(self._on_row_deleted)
        
        # 滚动视图（可滚动列）
        self._scroll_view = TableView()
        self._scroll_view.column_moved.connect(self._on_column_moved)
        self._scroll_view.row_deleted.connect(self._on_row_deleted)
        
        # 设置视图大小策略，确保滚动条正常工作
        self._fixed_view.setSizePolicy(QSizePolicy.Preferred, QSizePolicy.Expanding)
        self._scroll_view.setSizePolicy(QSizePolicy.Preferred, QSizePolicy.Expanding)
        
        # 连接滚动同步信号
        self._connect_scroll_sync()
        
        # 添加到分割器
        table_splitter.addWidget(self._fixed_view)
        table_splitter.addWidget(self._scroll_view)
        table_splitter.setSizes([300, 900])  # 初始宽度分配
        
        table_layout.addWidget(table_splitter)
        
        # 将表格Tab添加到Tab控件
        self.tab_widget.addTab(table_widget, "表格视图")
        
    def _setup_treeview_tab(self):
        """设置TreeView Tab"""
        # 创建TreeView Tab的widget
        tree_widget = QWidget()
        tree_layout = QVBoxLayout(tree_widget)
        
        # 创建TreeView
        self.tree_view = QTreeView()
        
        # 创建模型并设置到视图
        from src.frontend.dict_tree_model import DictTreeModel
        self.tree_model = DictTreeModel()
        self.tree_view.setModel(self.tree_model)
        
        # 添加TreeView到布局
        tree_layout.addWidget(self.tree_view)
        
        # 添加示例数据
        self._load_sample_tree_data()
        
        # 将TreeView Tab添加到Tab控件
        self.tab_widget.addTab(tree_widget, "树形视图")
        
    def _load_sample_tree_data(self):
        """加载示例树形数据"""
        sample_data = {
            "个人信息": {
                "姓名": "张三",
                "年龄": 30,
                "职业": "软件工程师",
                "联系方式": {
                    "电话": "13800138000",
                    "邮箱": "zhangsan@example.com",
                    "地址": {
                        "省份": "广东省",
                        "城市": "深圳市",
                        "详细地址": "南山区科技园"
                    }
                }
            },
            "工作经历": [
                {
                    "公司": "ABC科技有限公司",
                    "职位": "高级工程师",
                    "时间": "2020-2023"
                },
                {
                    "公司": "XYZ软件公司",
                    "职位": "技术主管",
                    "时间": "2023-至今"
                }
            ],
            "技能": [
                "Python",
                "PySide6",
                "JavaScript",
                "数据库设计"
            ]
        }
        
        self.tree_model.populate(sample_data)
        self.tree_view.expandAll()
        
        
    def _setup_statusbar(self):
        """设置状态栏"""
        self._status_bar = QStatusBar()
        self.setStatusBar(self._status_bar)
        
        # 状态标签
        self._status_label = QLabel("就绪")
        self._status_bar.addWidget(self._status_label)
        
        # 进度条
        self._progress_bar = QProgressBar()
        self._progress_bar.setVisible(False)
        self._status_bar.addPermanentWidget(self._progress_bar)
        
    def _setup_shortcuts(self):
        """设置快捷键"""
        # 文件操作快捷键
        open_shortcut = QShortcut(QKeySequence.Open, self)
        open_shortcut.activated.connect(self._open_file)
        
        save_shortcut = QShortcut(QKeySequence.Save, self)
        save_shortcut.activated.connect(self._save_file)
        
        # 编辑操作快捷键
        undo_shortcut = QShortcut(QKeySequence.Undo, self)
        undo_shortcut.activated.connect(self._undo)
        
        redo_shortcut = QShortcut(QKeySequence.Redo, self)
        redo_shortcut.activated.connect(self._redo)
        
        # 添加行/列快捷键
        add_row_shortcut = QShortcut(QKeySequence("Ctrl+N"), self)
        add_row_shortcut.activated.connect(self._add_row)
        
        add_col_shortcut = QShortcut(QKeySequence("Ctrl+Shift+C"), self)
        add_col_shortcut.activated.connect(self._add_column)
        
        insert_col_shortcut = QShortcut(QKeySequence("Ctrl+I"), self)
        insert_col_shortcut.activated.connect(self._insert_column)
        
        insert_row_shortcut = QShortcut(QKeySequence("Ctrl+Shift+N"), self)
        insert_row_shortcut.activated.connect(self._insert_row)
        
        # 行操作快捷键
        disable_rows_shortcut = QShortcut(QKeySequence("Ctrl+D"), self)
        disable_rows_shortcut.activated.connect(self._disable_selected_rows)
        
        enable_rows_shortcut = QShortcut(QKeySequence("Ctrl+E"), self)
        enable_rows_shortcut.activated.connect(self._enable_selected_rows)
        
        # 删除行快捷键
        delete_shortcut = QShortcut(QKeySequence.Delete, self)
        delete_shortcut.activated.connect(self._delete_selected_rows)
        
        # 复制快捷键 - 全局处理
        copy_shortcut = QShortcut(QKeySequence.Copy, self)
        copy_shortcut.activated.connect(self._copy_selection)
        
    def _init_table(self):
        """初始化表格"""
        # 创建表格模型
        self._model = TableModel(self._data_manager)
        
        # 为每个视图创建独立的模型实例
        self._fixed_model = TableModel(self._data_manager)
        self._scroll_model = TableModel(self._data_manager)
        
        # 设置模型到视图
        self._fixed_view.set_model(self._fixed_model)
        self._scroll_view.set_model(self._scroll_model)
        
        # 更新冻结列
        self._update_frozen_columns()
        
        # 设置视图显示范围
        self._update_view_ranges()
        
        # 连接信号
        self._fixed_view.cell_edited.connect(self._on_cell_edited)
        self._fixed_view.row_deleted.connect(self._on_row_deleted)
        self._fixed_view.column_moved.connect(self._on_column_moved)
        self._fixed_view.row_status_changed.connect(self._on_row_status_changed)
        self._fixed_view.add_row_requested.connect(self._add_row)
        self._fixed_view.insert_row_requested.connect(self._insert_row_at_position)
        self._fixed_view.delete_rows_requested.connect(self._delete_rows_from_view)
        
        self._scroll_view.cell_edited.connect(self._on_cell_edited)
        self._scroll_view.row_deleted.connect(self._on_row_deleted)
        self._scroll_view.column_moved.connect(self._on_column_moved)
        self._scroll_view.row_status_changed.connect(self._on_row_status_changed)
        self._scroll_view.add_row_requested.connect(self._add_row)
        self._scroll_view.insert_row_requested.connect(self._insert_row_at_position)
        self._scroll_view.delete_rows_requested.connect(self._delete_rows_from_view)
        
    def _open_file(self):
        """打开文件"""
        file_path, _ = QFileDialog.getOpenFileName(
            self, "打开CSV文件", "", "CSV文件 (*.csv);;所有文件 (*)"
        )
        
        if file_path:
            self._show_progress("正在加载文件...")
            
            if self._data_manager.load_csv_data(file_path):
                self._fixed_model.refresh_data()
                self._scroll_model.refresh_data()
                self._update_frozen_columns()
                self._update_view_ranges()
                self._hide_progress()
                self._status_label.setText(f"已加载文件: {os.path.basename(file_path)}")
            else:
                self._hide_progress()
                QMessageBox.critical(self, "错误", "无法加载文件")
                
    def _save_file(self):
        """保存文件"""
        # 这里可以实现自动保存到当前文件
        self._save_file_as()
        
    def _save_file_as(self):
        """另存为"""
        file_path, _ = QFileDialog.getSaveFileName(
            self, "保存CSV文件", "", "CSV文件 (*.csv);;所有文件 (*)"
        )
        
        if file_path:
            self._show_progress("正在保存文件...")
            
            if self._data_manager.save_csv_data(file_path):
                self._hide_progress()
                self._status_label.setText(f"已保存文件: {os.path.basename(file_path)}")
            else:
                self._hide_progress()
                QMessageBox.critical(self, "错误", "无法保存文件")
                
    def _add_row(self):
        """添加行"""
        if not self._fixed_model:
            return
            
        data, headers = self._data_manager.get_data()
        empty_row = [""] * len(headers)
        
        # 直接操作数据管理器
        if self._data_manager.add_row(empty_row):
            # 记录撤销操作
            new_row = self._data_manager.get_row_count() - 1
            self._undo_manager.add_operation(
                OperationType.INSERT_ROW,
                {
                    'row_index': new_row,
                    'row_data': empty_row.copy()
                },
                "添加新行"
            )
            
            # 更新状态
            self._update_status()
            
    def _insert_row_at_position(self, position: int, row_data: list):
        """在指定位置插入行"""
        if not self._fixed_model:
            return
            
        # 直接操作数据管理器
        if self._data_manager.insert_row(position, row_data):
            # 记录撤销操作
            self._undo_manager.add_operation(
                OperationType.INSERT_ROW,
                {
                    'row_index': position,
                    'row_data': row_data.copy()
                },
                f"在位置 {position} 插入行"
            )
            
            # 更新状态
            self._update_status()
            
    def _disable_selected_rows(self):
        """禁用选中的行"""
        if not self._fixed_model:
            return
            
        selected_rows = self._scroll_view.get_selected_rows()
        if not selected_rows:
            selected_rows = self._fixed_view.get_selected_rows()
            
        if selected_rows:
            # 过滤掉已经禁用的行
            enabled_rows = [row for row in selected_rows if not self._fixed_model.is_row_disabled(row)]
            
            if enabled_rows:
                if self._fixed_model.disable_rows(enabled_rows):
                    # 记录撤销操作
                    self._undo_manager.add_operation(
                        OperationType.UPDATE_ROW_STATUS,
                        {
                            'row_indices': enabled_rows.copy(),
                            'action': 'disable'
                        },
                        f"禁用 {len(enabled_rows)} 行"
                    )
                    
                    # 更新状态
                    self._update_status()
                    
    def _enable_selected_rows(self):
        """启用选中的行"""
        if not self._fixed_model:
            return
            
        selected_rows = self._scroll_view.get_selected_rows()
        if not selected_rows:
            selected_rows = self._fixed_view.get_selected_rows()
            
        if selected_rows:
            # 过滤出已经禁用的行
            disabled_rows = [row for row in selected_rows if self._fixed_model.is_row_disabled(row)]
            
            if disabled_rows:
                if self._fixed_model.enable_rows(disabled_rows):
                    # 记录撤销操作
                    self._undo_manager.add_operation(
                        OperationType.UPDATE_ROW_STATUS,
                        {
                            'row_indices': disabled_rows.copy(),
                            'action': 'enable'
                        },
                        f"启用 {len(disabled_rows)} 行"
                    )
                    
                    # 更新状态
                    self._update_status()
            
    def _add_column(self):
        """添加列"""
        if not self._fixed_model:
            return
            
        header, ok = QInputDialog.getText(self, "添加列", "请输入列名:")
        if ok and header:
            if self._fixed_model.add_column(header):
                # 记录撤销操作
                self._undo_manager.add_operation(
                    OperationType.ADD_COLUMN,
                    {
                        'col_index': self._data_manager.get_column_count() - 1,
                        'header': header
                    },
                    f"添加列: {header}"
                )
                
                # 更新视图显示范围
                self._update_view_ranges()
                
                # 更新状态
                self._update_status()
                
    def _insert_row(self):
        """插入行"""
        if not self._fixed_model:
            return
            
        # 获取当前选中的行
        selected_rows = self._scroll_view.get_selected_rows()
        if not selected_rows:
            selected_rows = self._fixed_view.get_selected_rows()
            
        current_row = selected_rows[0] if selected_rows else 0
        total_rows = self._data_manager.get_row_count()
        
        # 创建插入行对话框
        from frontend.insert_row_dialog import InsertRowDialog
        dialog = InsertRowDialog(current_row, total_rows, self)
        if dialog.exec_() == QDialog.Accepted:
            result = dialog.get_row_info()
            if result:
                count, position, fill_mode_index = result
                
                # 获取表头以创建行数据
                data, headers = self._data_manager.get_data()
                empty_row = [""] * len(headers)
                
                # 根据填充模式创建行数据
                if fill_mode_index == 1 and position > 0:  # 复制上一行
                    if position - 1 < len(data):
                        row_data = data[position - 1].copy()
                    else:
                        row_data = empty_row
                elif fill_mode_index == 2 and position < len(data):  # 复制当前行
                    row_data = data[position].copy()
                else:  # 空白值或智能默认值
                    row_data = empty_row
                
                # 插入行
                if self._data_manager.insert_row(position, row_data):
                    # 两个模型都需要通知行插入
                    self._fixed_model.beginInsertRows(QModelIndex(), position, position)
                    self._fixed_model.endInsertRows()
                    self._scroll_model.beginInsertRows(QModelIndex(), position, position)
                    self._scroll_model.endInsertRows()
                    
                    # 记录撤销操作
                    self._undo_manager.add_operation(
                        OperationType.INSERT_ROW,
                        {
                            'row_index': position,
                            'row_data': row_data.copy()
                        },
                        f"在位置 {position} 插入行"
                    )
                    
                    # 更新状态
                    self._update_status()
    def _insert_column(self):
        """插入列"""
        total_columns = self._data_manager.get_column_count()
        dialog = InsertColumnDialog(total_columns, self)
        if dialog.exec_() == QDialog.Accepted:
            result = dialog.get_column_info()
            if result:
                position, header, default_value = result
                # 只让一个模型插入列，另一个模型只刷新
                if self._fixed_model.insert_column(position, header, default_value):
                    self._scroll_model.refresh_data()
                    # 记录撤销操作
                    self._undo_manager.add_operation(
                        OperationType.INSERT_COLUMN,
                        {
                            'position': position,
                            'header': header,
                            'default_value': default_value,
                            'col_index': position
                        },
                        f"插入列 {header} 于位置 {position}"
                    )
                    self._update_status()
                else:
                    QMessageBox.warning(self, "插入失败", "插入列失败，请检查参数")
                
    def _delete_rows_from_view(self, selected_rows: list):
        """处理来自 TableView 的删除行请求"""
        if not selected_rows:
            return
            
        # 按降序删除，避免索引变化
        deleted_count = 0
        for row in selected_rows:
            data, _ = self._data_manager.get_data()
            row_data = data[row].copy()

            # 1. 所有模型先 beginRemoveRows
            self._fixed_model.beginRemoveRows(QModelIndex(), row, row)
            self._scroll_model.beginRemoveRows(QModelIndex(), row, row)
            # 2. 数据管理器删除数据
            self._data_manager.remove_row(row)
            # 3. 所有模型 endRemoveRows
            self._fixed_model.endRemoveRows()
            self._scroll_model.endRemoveRows()

            deleted_count += 1
            # 记录撤销操作
            self._undo_manager.add_operation(
                OperationType.DELETE_ROW,
                {
                    'row_index': row,
                    'row_data': row_data
                },
                f"删除行 {row}"
            )
        # 更新状态
        self._update_status()

    def _delete_selected_rows(self):
        """删除选中的行"""
        if not self._fixed_model:
            return
            
        selected_rows = self._scroll_view.get_selected_rows()
        if not selected_rows:
            selected_rows = self._fixed_view.get_selected_rows()
            
        if selected_rows:
            # 确认删除
            reply = QMessageBox.question(
                self, 
                "确认删除", 
                f"确定要删除选中的 {len(selected_rows)} 行吗？",
                QMessageBox.Yes | QMessageBox.No,
                QMessageBox.No
            )
            
            if reply == QMessageBox.Yes:
                # 按降序删除，避免索引变化
                deleted_count = 0
                for row in sorted(selected_rows, reverse=True):
                    data, _ = self._data_manager.get_data()
                    row_data = data[row].copy()

                    # 1. 所有模型先 beginRemoveRows
                    self._fixed_model.beginRemoveRows(QModelIndex(), row, row)
                    self._scroll_model.beginRemoveRows(QModelIndex(), row, row)
                    # 2. 数据管理器删除数据
                    self._data_manager.remove_row(row)
                    # 3. 所有模型 endRemoveRows
                    self._fixed_model.endRemoveRows()
                    self._scroll_model.endRemoveRows()

                    deleted_count += 1
                    # 记录撤销操作
                    self._undo_manager.add_operation(
                        OperationType.DELETE_ROW,
                        {
                            'row_index': row,
                            'row_data': row_data
                        },
                        f"删除行 {row}"
                    )
                # 更新状态
                self._update_status()
                
    def _set_column_markers(self):
        """设置列标识"""
        if not self._fixed_model:
            return
            
        data, headers = self._data_manager.get_data()
        current_marked = self._data_manager.get_marked_columns()
        
        from src.column_marker_dialog import ColumnMarkerDialog
        dialog = ColumnMarkerDialog(headers, current_marked, self)
        if dialog.exec() == QDialog.Accepted:
            marked_columns = dialog.get_marked_columns()
            
            # 检查标记是否发生变化，避免不必要的操作
            if marked_columns != current_marked:
                # 记录撤销操作
                self._undo_manager.add_operation(
                    OperationType.MARK_COLUMNS,
                    {
                        'old_marked': current_marked.copy(),
                        'new_marked': marked_columns.copy()
                    },
                    "设置列标识"
                )
                
                # 更新标记列（通过DataManager触发事件）
                self._data_manager.set_marked_columns(marked_columns)

    def _show_change_history(self):
        """显示变更历史"""
        dialog = ChangeHistoryDialog(self._data_manager, self)
        dialog.exec_()
    
    def _show_record(self):
        """显示修改记录"""
        # 获取所有被修改的行信息
        modified_rows = self._data_manager.get_modified_rows_summary()
        
        if not modified_rows:
            QMessageBox.information(self, "提示", "当前没有修改记录。")
            return
        
        # 获取表头
        headers = self._data_manager.get_headers()
        
        # 显示Record对话框
        dialog = RecordDialog(modified_rows, headers, self)
        result = dialog.exec_()
        
        # 如果用户选择清空记录
        if result == QDialog.Accepted:
            self._clear_modification_records()
    
    def _clear_modification_records(self):
        """清空修改记录"""
        # 清空数据管理器中的修改标记
        self._data_manager.clear_modification_flags()
        
        # 刷新表格视图
        if self._fixed_model:
            self._fixed_model.refresh_data()
        if self._scroll_model:
            self._scroll_model.refresh_data()
        
        # 更新状态栏
        self._update_status()
        
        QMessageBox.information(self, "成功", "所有修改记录已清空。")
        
    def _show_about(self):
        """显示关于对话框"""
        QMessageBox.about(
            self, 
            "关于 Qtable", 
            "Qtable - 数据表格编辑器\n\n"
            "版本: 2.0\n"
            "功能: 前后端分离架构，支持数据修改记录和颜色标记"
        )
        
    def _undo(self):
        """撤销操作"""
        if self._undo_manager.undo():
            if self._fixed_model:
                self._fixed_model.refresh_data()
            if self._scroll_model:
                self._scroll_model.refresh_data()
            self._update_frozen_columns()
            self._update_view_ranges()
            self._update_status()
            self._update_undo_redo_actions()
            # 强制刷新视图
            if self._fixed_view:
                self._fixed_view.refresh_view()
            if self._scroll_view:
                self._scroll_view.refresh_view()
            
    def _redo(self):
        """重做操作"""
        if self._undo_manager.redo():
            if self._fixed_model:
                self._fixed_model.refresh_data()
            if self._scroll_model:
                self._scroll_model.refresh_data()
            self._update_frozen_columns()
            self._update_view_ranges()
            self._update_status()
            self._update_undo_redo_actions()
            # 强制刷新视图
            if self._fixed_view:
                self._fixed_view.refresh_view()
            if self._scroll_view:
                self._scroll_view.refresh_view()

    def _on_column_moved(self, logical_index: int, old_visual_index: int, new_visual_index: int):
        """列移动事件"""
        if not self._fixed_model:
            return
            
        # 获取当前列顺序
        current_order = self._data_manager.get_column_order()
        
        # 检查是否真的需要改变顺序
        if old_visual_index == new_visual_index:
            return
            
        # 创建新的列顺序
        new_order = current_order.copy()
        if old_visual_index < len(new_order) and new_visual_index < len(new_order):
            # 移动列
            col_to_move = new_order[old_visual_index]
            new_order.pop(old_visual_index)
            new_order.insert(new_visual_index, col_to_move)
            
            # 检查新顺序是否与当前顺序相同
            if new_order == current_order:
                return
            
            # 记录撤销操作
            self._undo_manager.add_operation(
                OperationType.REORDER_COLUMNS,
                {
                    'old_order': current_order.copy(),
                    'new_order': new_order.copy()
                },
                f"移动列 {logical_index}"
            )
            
            # 更新列顺序 - 使用静默模式避免递归
            self._fixed_model.set_column_order(new_order, silent=True)
            self._scroll_model.set_column_order(new_order, silent=True)
            self._update_frozen_columns()
            
    def _on_row_deleted(self, row_index: int):
        """行删除事件"""
        # 这里可以添加额外的处理逻辑
        pass
    
    def _on_row_status_changed(self, row_indices: list, action: str):
        """处理行状态变化（禁用/启用）"""
        if not self._fixed_model:
            return
            
        if action == 'disable':
            if self._fixed_model.disable_rows(row_indices):
                # 记录撤销操作
                self._undo_manager.add_operation(
                    OperationType.UPDATE_ROW_STATUS,
                    {
                        'row_indices': row_indices.copy(),
                        'action': 'disable'
                    },
                    f"禁用 {len(row_indices)} 行"
                )
                # 更新状态
                self._update_status()
                
        elif action == 'enable':
            if self._fixed_model.enable_rows(row_indices):
                # 记录撤销操作
                self._undo_manager.add_operation(
                    OperationType.UPDATE_ROW_STATUS,
                    {
                        'row_indices': row_indices.copy(),
                        'action': 'enable'
                    },
                    f"启用 {len(row_indices)} 行"
                )
                # 更新状态
                self._update_status()
    
    def _on_cell_edited(self, row: int, col: int, value: str):
        """处理单元格编辑"""
        # 获取旧值
        old_value = self._data_manager.get_cell_data(row, col)
        
        # 如果值发生了变化，记录撤销操作
        if old_value != value:
            self._undo_manager.add_operation(
                OperationType.UPDATE_CELL,
                {
                    'row': row,
                    'col': col,
                    'old_value': old_value,
                    'new_value': value
                },
                f"更新单元格 [{row}, {col}]: '{old_value}' -> '{value}'"
            )
        
        # 更新状态栏
        self._update_status()
        
    def _connect_scroll_sync(self):
        """连接滚动同步"""
        # 连接垂直滚动条同步
        self._fixed_view.verticalScrollBar().valueChanged.connect(
            self._scroll_view.verticalScrollBar().setValue
        )
        self._scroll_view.verticalScrollBar().valueChanged.connect(
            self._fixed_view.verticalScrollBar().setValue
        )
        
        # 连接水平滚动条同步（只同步右侧视图的水平滚动）
        self._scroll_view.horizontalScrollBar().valueChanged.connect(
            self._on_horizontal_scroll_changed
        )
        
    def _on_horizontal_scroll_changed(self, value):
        """水平滚动改变事件"""
        # 这里可以添加水平滚动的特殊处理逻辑
        pass
        
    def _update_frozen_columns(self):
        """更新冻结列"""
        if not self._fixed_model or not self._scroll_model:
            return
            
        marked_columns = self._data_manager.get_marked_columns()
        
        if marked_columns:
            # 如果有标记的列，冻结这些列
            self._frozen_columns = len(marked_columns)
        else:
            # 否则冻结前3列
            self._frozen_columns = min(3, self._data_manager.get_column_count())
            
        # 更新视图
        self._fixed_view.horizontalHeader().reset()
        self._scroll_view.horizontalHeader().reset()
        self._fixed_view.horizontalHeader().setVisible(True)
        self._scroll_view.horizontalHeader().setVisible(True)
        
        # 更新视图显示范围
        self._update_view_ranges()
        
    def _update_view_ranges(self):
        """更新视图显示范围"""
        if not self._fixed_model or not self._scroll_model:
            return
            
        marked_columns = self._data_manager.get_marked_columns()
        total_columns = self._data_manager.get_column_count()
        
        if marked_columns:
            # 左侧视图显示标记的列
            marked_list = sorted(list(marked_columns))
            self._fixed_view.set_column_range(marked_list)
            
            # 右侧视图显示其余列
            remaining_columns = [i for i in range(total_columns) if i not in marked_columns]
            self._scroll_view.set_column_range(remaining_columns)
        else:
            # 如果没有标记列，左侧显示前3列，右侧显示其余列
            frozen_count = min(3, total_columns)
            left_columns = list(range(frozen_count))
            right_columns = list(range(frozen_count, total_columns))
            
            self._fixed_view.set_column_range(left_columns)
            self._scroll_view.set_column_range(right_columns)
        
    def _show_progress(self, message: str):
        """显示进度条"""
        self._progress_bar.setVisible(True)
        self._progress_bar.setRange(0, 0)  # 不确定进度
        self._status_label.setText(message)
        
    def _hide_progress(self):
        """隐藏进度条"""
        self._progress_bar.setVisible(False)
        
    def _update_status(self):
        """更新状态栏"""
        if not self._fixed_model:
            return
            
        row_count = self._data_manager.get_row_count()
        col_count = self._data_manager.get_column_count()
        modified_cells = len(self._data_manager.get_modified_cells())
        disabled_rows = len(self._data_manager.get_disabled_rows())
        
        status_text = f"行: {row_count}, 列: {col_count}"
        if modified_cells > 0:
            status_text += f", 修改: {modified_cells}"
        if disabled_rows > 0:
            status_text += f", 禁用: {disabled_rows}"
            
        # 更新撤销/重做状态
        if self._undo_manager.can_undo():
            undo_desc = self._undo_manager.get_undo_description()
            if undo_desc:
                status_text += f" | 撤销: {undo_desc}"
                
        if self._undo_manager.can_redo():
            redo_desc = self._undo_manager.get_redo_description()
            if redo_desc:
                status_text += f" | 重做: {redo_desc}"
                
        self._status_label.setText(status_text)
        self._update_undo_redo_actions()  # 确保更新撤销/重做动作状态

    def _update_undo_redo_actions(self):
        """更新撤销/重做操作的状态"""
        # 更新菜单项和工具栏按钮的状态
        if hasattr(self, '_undo_action') and hasattr(self, '_redo_action'):
            self._undo_action.setEnabled(self._undo_manager.can_undo())
            self._redo_action.setEnabled(self._undo_manager.can_redo())

    def _copy_selection(self):
        """全局复制功能 - 复制所有列的数据"""
        if not self._fixed_model:
            return
            
        # 获取选中的行（从任意一个视图）
        selected_rows = set()
        
        # 从固定视图获取选中行
        if self._fixed_view:
            fixed_rows = self._fixed_view.get_selected_rows()
            selected_rows.update(fixed_rows)
        
        # 从滚动视图获取选中行
        if self._scroll_view:
            scroll_rows = self._scroll_view.get_selected_rows()
            selected_rows.update(scroll_rows)
        
        if not selected_rows:
            return
            
        # 获取完整的数据和表头
        data, headers = self._data_manager.get_data()
        
        # 按行列组织数据（包含所有列）
        rows_data = {}
        for row in selected_rows:
            if row < len(data):
                rows_data[row] = {}
                for col in range(len(data[row])):
                    rows_data[row][col] = str(data[row][col])
        
        if not rows_data:
            return
            
        # 获取选中的行范围
        selected_rows = sorted(rows_data.keys())
        total_cols = len(headers) if headers else 0
        
        # 创建CSV格式的文本
        csv_lines = []
        for row in selected_rows:
            row_data = []
            for col in range(total_cols):
                value = rows_data[row].get(col, "")
                # 处理包含逗号或引号的值
                value_str = str(value)
                if ',' in value_str or '"' in value_str or '\n' in value_str:
                    escaped_value = value_str.replace('"', '""')
                    value_str = f'"{escaped_value}"'
                row_data.append(value_str)
            csv_lines.append(','.join(row_data))
        
        csv_text = '\n'.join(csv_lines)
        
        # 创建制表符分隔的文本（用于Excel粘贴）
        tsv_lines = []
        for row in selected_rows:
            row_data = []
            for col in range(total_cols):
                value = rows_data[row].get(col, "")
                row_data.append(str(value))
            tsv_lines.append('\t'.join(row_data))
        
        tsv_text = '\n'.join(tsv_lines)
        
        # 复制到剪贴板
        from PySide6.QtGui import QClipboard, QGuiApplication
        clipboard = QGuiApplication.clipboard()
        
        # 设置多种格式的剪贴板数据
        clipboard.setText(csv_text)
        
        # 设置HTML格式
        html_text = "<table>"
        for row in selected_rows:
            html_text += "<tr>"
            for col in range(total_cols):
                value = rows_data[row].get(col, "")
                html_text += "<td>" + str(value) + "</td>"
            html_text += "</tr>"
        html_text += "</table>"
        
        mime_data = clipboard.mimeData()
        mime_data.setText(csv_text)
        mime_data.setHtml(html_text)
        
        # 显示状态提示
        QMessageBox.information(self, "复制成功", f"已复制 {len(selected_rows)} 行 {total_cols} 列数据到剪贴板")
